$(document).ready(function() {
	
	var pageData = {
		page: 1,
		size: 8,
		search: {}
	}
	var gameList;
	var isAdd = undefined;
	var config = {};

	if(!SELFID) {
		window.location = HOST + '?path=https://worldcup.dmpb.com.cn/front/travel_list.html';
		return;
	}

	$.init();
	fetchIsAdd(SELFID, function(result) {
		isAdd = result;
		renderList();
	});
	fetchRemindList(function(data) {
		if(data.commentNotViewNum + data.dateNotViewNum + data.dateResultNotViewNum + data.topNotViewNum + data.viewNotViewNum > 0) {
			$('.button-dynamic em').show();
		}
	});
	createCalendar({
		$wrapper: $('.search-date')
	});

	$(document).on('click', '.j-look', lookInfoHandle);
	$(document).on('click', '.j-self', redirectHandle);
	$(document).on('click', '.filter-nav a', showFilterSearch);
	$(document).on('click', '.j-clear', clearHandle);
	$(document).on('click', '.j-search', searchHandle);
	$(document).on('click', '.j-agree', agreeHandle);
	$(document).on('click', '.j-dynamic', dynamicHandle);
	$(document).on('click', '.list-mask', hideMaskHandle);
	$(document).on('click', '.search-other .button', toggleBtnHandle);
	$(document).on('click', '.search-hot .button', searchHotHandle);
	$(document).on('click', '.search-ass li', chooseHandle);
	$('.infinite-scroll-bottom').on('infinite', infiniteHandle());
	$(document).on('input propertychange', '.search-city input', throttle(inputCityHandle, 500, 1000));
	$(document).on('input propertychange', '.search-match input', throttle(inputMatchHandle, 500, 1000));
	$(document).on('focus', '.search-match input', focusMatchHandle);
	$(document).on('blur', '.search-match input', blurMatchHandle);

	getConfig(function(result) {
		if(result.length == 0) {
			initGuide();
			return;
		}
		var obj = JSON.parse(result);
		if(typeof obj == 'object' && obj['guide'] == VERSON) {
			config = obj;
			return;
		}
		initGuide();
	});

	function getConfig(callback) {
		$.ajax({
			url: HOST + '/api/config/get',
			data: {
				openid: SELFID
			},
			success: function(res) {
				callback && callback(res.content);
			},
			error: function() {
				callback && callback('');
			}
		});
	}

	function setConfig() {
		config['guide'] = VERSON;
		$.ajax({
			url: HOST + '/api/config/set',
			type: 'post',
			data: JSON.stringify({
				'openid': SELFID,
				'config': JSON.stringify(config)
			}),
			success: function(res) {
			},
		});
	}

	function initGuide() {
		new Guide({
			arr: [{
				title: '动态',
				class: 'guide_dynamic',
				desc: '在这里查看约伴动态'
			},{
				title: '&nbsp;&nbsp;我&nbsp;&nbsp;',
				class: 'guide_me',
				desc: '在这里填写个人信息'
			},{
				title: '<img src="./img/nav.png">',
				class: 'guide_filter',
				desc: '可根据城市、比赛、时间、年龄筛选球友信息'
			},{
				title: '<img src="./img/item.png">',
				class: 'guide_card',
				desc: '可点击这里查看球友详细信息进行约伴，每日上限为6次'
			},{
				title: '<img src="./img/call.png">',
				class: 'guide_top',
				desc: '可点击这里为球友置顶，每日上限为6次'
			}],
			complete: function() {
				setConfig();
			}
		});
	}

	function focusMatchHandle(e) {
		var $target = $(e.target);
		var $parent = $target.closest('.search-item');
		var $list = $('.search-ass ul', $parent);
		$('.search-hot', $parent).hide();
		$('.search-ass', $parent).show();
		fetchAll(function() {
			var html = '';
			gameList.forEach(function(item) {
				var match = item.homeTeam + ' vs ' + item.awayTeam + '&nbsp;&nbsp;&nbsp;&nbsp;编号：' + item.id;
				html += ('<li data-id="'+item.id+'">'+match+'</li>');
			});
			$list.html(html);
		});
	}

	function blurMatchHandle(e) {
		setTimeout(function() {
			$('.search-match .search-hot').show();
			$('.search-match .search-ass').hide();
		}, 0);
	}

	function inputMatchHandle(e) {
		var $target = $(e.target);
		var $parent = $target.closest('.search-item');
		var val = $target.val().trim();
		var $list = $('.search-ass ul', $parent);
		$('.search-hot', $parent).hide();
		$('.search-ass', $parent).show();
		fetchAll(function() {
			var html = '';
			gameList.forEach(function(item) {
				var match = item.homeTeam + ' vs ' + item.awayTeam + '&nbsp;&nbsp;&nbsp;&nbsp;编号：' + item.id;
				var matchid = item.id + '';
				if(match.indexOf(val) > -1 || matchid.indexOf(val) > -1) {
					match = match.replace(val, '<em>'+val+'</em>');
					html += ('<li data-id="'+item.id+'">'+match+'</li>');
				}
			});
			$list.html(html);
		});
	}

	function inputCityHandle(e) {
		var MAX = 5;
		var $target = $(e.target);
		var $parent = $target.closest('.search-item')
		var val = $target.val().trim();
		var $list = $('.search-ass ul', $parent);
		if(val) {
			$('.search-hot', $parent).hide();
			$('.search-ass', $parent).show();
		}else{
			$('.search-hot', $parent).show();
			$('.search-ass', $parent).hide();
		}
		fetchCity(val, function(citys) {
			var html = '';
			citys = citys.slice(0, 5);
			citys.forEach(function(item) {
				var city = item;
				city = city.replace(val, '<em>'+val+'</em>');
				html += ('<li data-id="'+item+'">'+city+'</li>');
			});
			$list.html(html||'');
		});
	}

	function chooseHandle(e) {
		var $target = $(e.currentTarget);
		var $parent = $target.closest('.search-item');
		$('input', $parent).val($target.data('id'));
		$('.search-hot', $parent).show();
		$('.search-ass', $parent).hide();
	}

	function fetchAll(callback) {
		if(gameList) {
			callback && callback();
			return;
		}
		$.ajax({
			url: HOST + '/api/game/list',
			success: function(res) {
				gameList = res.content;
				callback && callback();
			}
		});
	}

	function fetchCity(keyword, callback) {
		if(!keyword) {
			callback && callback([]);
			return;
		}
		$.ajax({
			url: HOST + '/api/search/keyword/city?city='+keyword,
			success: function(res) {
				callback && callback(res.content);
			}
		})
	}

	function fetchRemindList(callback) {
        $.ajax({
            type: 'GET',
            url: HOST + '/api/user/remind/survey',
            data: {
            	openid: SELFID
            },
            success: function(res) {
                callback && callback(res.content);
            }
        });
    }

	function showFilterSearch(e) {
		var $target = $(e.target);
		e.stopPropagation();
		$('.list-mask').show();
		$target.addClass('active').siblings().removeClass('active');
		setTimeout(function() {
			$('.search-box').addClass('search-box-show');
			$('.list-mask').addClass('list-mask-over');
			$('.search-item').hide();
			$('.search-' + $target.data('search')).show();
		}, 100);
	}

	function toggleBtnHandle(e) {
		$(e.target).toggleClass('button-light');
	}

	function lookInfoHandle(e) {
		if(!isAdd) {
			$.alert('您还没有录入行程信息，请点击右上角"我"按钮录入行程');
			return;
		}
		var id = $(e.currentTarget).closest('.card').data('id');
		if(id == SELFID) {
			$('.j-self')[0].click();
			return;
		}
		if($(e.currentTarget).closest('.card').data('apply')){
			window.location = './travel_info.html?targetid='+id+'&selfid='+SELFID;
			return;
		}
		fetchMax(function(amount) {
			if(amount == 0) {
				$.alert('您今天没有查看详情的机会了');
				return;
			}
			$.confirm('您今天还有' + amount + '次查看详情的机会', function(isAdd){
				if(isAdd) {
					window.location = './travel_info.html?targetid='+id+'&selfid='+SELFID;
				}
			})
		});
	}

	function createCalendar(options){
		var date = new Date();
		options.$wrapper.calendar();
	}

	function redirectHandle(e) {
		fetchIsAdd(SELFID, function(isAdd) {
			if(isAdd) {
				window.location = './travel_info.html';
			}else{
				window.location = './travel_insert.html'
			}
		});
	}

	function clearHandle(e) {
		$('.search-box input').val('');
		$('.search-hot').show();
		$('.search-ass').hide().find('ul').html('');
		$('.search-box .button').addClass('button-light');
		pageData.search = {};
	}

	function searchHandle(data) {
		pageData.page = 1;
		var ages = [];
		$('.many-item-age .button').each(function (item) {
			var $btn = $(this);
			if(!$btn.hasClass('button-light')){
				ages.push($btn.data('val'));
			}
		});
		pageData.search['age'] = ages;
		var genders = [];
		$('.many-item-gender .button').each(function (item) {
			var $btn = $(this);
			if(!$btn.hasClass('button-light')){
				genders.push($btn.data('val'));
			}
		});
		pageData.search['gender'] = genders;
		if($('.search-date').val()) {
			pageData.search['date'] = [$('.search-date').val()];
		}
		var citys =[];
		if($('.search-city input').val()) {
			citys.push($('.search-city input').val());
		}
		$('.search-city .button').each(function (item) {
			var $btn = $(this);
			if(!$btn.hasClass('button-light')){
				citys.push($btn.data('val'));
			}
		});
		pageData.search['city'] = citys;
		var matchs =[];
		if($('.search-match input').val()) {
			matchs.push($('.search-match input').val());
		}
		$('.search-match .button').each(function (item) {
			var $btn = $(this);
			if(!$btn.hasClass('button-light')){
				matchs.push($btn.data('val'));
			}
		});
		pageData.search['match'] = matchs;
		renderList();
		hideMaskHandle();
	}

	function searchHotHandle(e) {
		var $target = $(e.target);
		var $parent = $target.closest('.search-item');
		$('input', $parent).val($target.data('val'));
		searchHandle();
	}

	function hideMaskHandle() {
		$('.search-box').removeClass('search-box-show');
		$('.list-mask').removeClass('list-mask-over').hide();
	}

	function inputChangeHandle() {
		console.log($('#search').val())
	}

	function agreeHandle(e) {
		var $target = $(e.target);
		if(!isAdd) {
			$.alert('您还没有录入行程信息，请点击右上角"我"按钮录入行程');
			return;
		}
		//正在ajax或已经点过赞或已经申请过
		if($target.hasClass('agree-active') || $target.hasClass('ajaxing')) {
			return;
		}
		$target.addClass('ajaxing');
		$.ajax({
			url: HOST + '/api/travel/support',
			type: 'post',
			data: JSON.stringify({
				openid: SELFID,
				supportedOpenid: $target.closest('.card').data('id')
			}),
			success: function(res){
				if(res.content == 'success') {
					$(e.target).addClass('agree-active');
					$target.find('em').html(+$target.find('em').html()+1);
				}else{
					$.alert(res.content);
				}
				$(e.target).removeClass('ajaxing');
			}
		});
	}

	function dynamicHandle() {
		window.location = './travel_remind.html';
	}

	function fetchMax(callback) {
		$.ajax({
			type: 'GET',
			url: HOST + '/api/travel/remainViewNum?openid=' + SELFID,
			success: function(res) {
				callback && callback(res.content);
			},
			error: function() {
				callback(3);
			}
		});
	}

	function renderList() {
		fetchList(function(list) {
			var div = document.createElement('div');
			var content = list.reduce(function(memo, item) {
				return memo + getItemHtml(item);
			}, '');
			if(pageData.page == 1) {
				$('.content .list').html(content || '<div class="no-data">暂无数据</div>');
			}else{
				$('.content .list').append(content);
			}
			$('.content .infinite-box').html(list.length == pageData.size ? '<div class="infinite-scroll-preloader"><div class="preloader"></div></div>' : '');
		});
	}

	function fetchList(callback) {
		var type, val;
		var temp = '?openid=' + SELFID + '&page=' + pageData.page + '&size=' + pageData.size;
		for(var type in pageData.search) {
			val = pageData.search[type];
			if(val && val.length > 0) {
				temp = temp + '&' + type + '=' + (typeof val =='string' ? val : val.join('|'));
			}
		}
		$.ajax({
			type: 'GET',
			url: HOST + '/api/travel/list' + temp,
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function fetchIsAdd(id, callback) {
		if(isAdd !== undefined) {
			callback && callback(isAdd);
			return;
		}
		$.ajax({
			type: 'GET',
			url: HOST + '/api/travel/haveTravel?openid=' + id,
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function infiniteHandle() {
        var loading = false;
        var I = 0;
        return function() {
            if(loading || $('.infinite-scroll-preloader').length == 0) {
                return;
            }
            loading = true;
            if(I) {
                clearTimeout(I);
            }
            I = setTimeout(function() {
            	pageData.page += 1;
                renderList();
                loading = false;
            }, 500);
        }
    }

	function getItemHtml(data) {
		return [
			'<div class="content-item card" data-id="'+data.openid.openid+'" data-apply="'+(data.isApply||data.isDate)+'">',
				'<div class="card-content j-look">',
					'<div class="card-content-inner">',
						'<div>',
							'<span class="name">' + data.name + '</span>',
							'<span class="sex">'+['', '男', '女'][data.gender]+'</span>',
							'<em>|</em>',
							'<span class="age">'+data.age+'岁</span>',
							'<em>|</em>',
							'<span class="team">' + (data.supportTeams.join(',')||'无球队') + '</span>',
							'<em>|</em>',
							'<span class="amount">' + data.peerNum + '人</span>',
						'</div>',
						'<div>',
							'<span class="watch">观赛信息:</span>',
							'<span class="ticket">' + data.matches.join(' ') + '</span>',
						'</div>',
						'<div>',
							'<span class="time">' + data.startDate + '&nbsp;-&nbsp;' + data.returnDate + '</span>',
							'<em>|</em>',
							'<span class="position">' + data.toCity + '</span>',
						'</div>',
						'<div>',
							'<span class="intro">简介:</span>',
							'<span class="desc">' + (data.description||'暂无简介') + '</span>',
						'</div>',
					'</div>',
				'</div>',
				'<div class="j-agree agree-btn '+(data.isUp?'agree-active':'')+'"><em>'+(data.upNum)+'</em>顶</div>',
			'</div>'
		].join('')
	}

})
